<template>
  <div class="sales-container">
    <el-card>
      <template #header>
        <div class="card-header">System Data</div>
      </template>

      <!-- 标签页 -->
      <el-tabs type="border-card">
        <!-- 第一个标签页：销售数据 -->
        <el-tab-pane label="Sales Data">
          <el-form-item>
            <el-button
                type="success"
                @click="predictSales"
                :loading="isPredicting"
                :disabled="!saleTrend"
            >
              Predict Sales
            </el-button>
          </el-form-item>

          <!-- 原有的销售数据内容 -->
          <div class="date-filter">
            <el-form :inline="true">
              <el-form-item label="Start Date">
                <el-date-picker
                    v-model="startDate"
                    type="datetime"
                    placeholder="Select Start Date"
                    :clearable="true"
                />
              </el-form-item>
              <el-form-item label="End Date">
                <el-date-picker
                    v-model="endDate"
                    type="datetime"
                    placeholder="Select End Date"
                    :clearable="true"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                    type="primary"
                    @click="fetchSalesDataWithDateRange"
                    :loading="isLoading"
                    :disabled="!startDate || !endDate"
                >
                  Filter by Date Range
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <div class="total-sales">
            <el-statistic title="Total Sales" :value="detailedSale?.totalSales || 0" />
          </div>

          <el-table
              :data="saleEntries"
              border
              v-loading="isLoading"
              style="width: 100%"
          >
            <el-table-column prop="0" label="Product ID" width="180" />
            <el-table-column prop="1" label="Quantity Sold" width="180" />

            <el-table-column label="Product Name">
              <template #default="{ row }">
                {{ detailedSale?.productDetail.get(row[0])?.name || 'N/A' }}
              </template>
            </el-table-column>

            <el-table-column label="Product Price">
              <template #default="{ row }">
                {{ detailedSale?.productDetail.get(row[0])?.price || 'N/A' }}
              </template>
            </el-table-column>
          </el-table>

          <div class="select-product" style="margin: 20px 0;">
            <el-select
                v-model="selectedProductId"
                placeholder="Select a Product"
                @change="fetchSalesTrend"
                :disabled="!detailedSale"
            >
              <el-option label="All Products" :value="0" />
              <el-option
                  v-for="[id, product] in productEntries"
                  :key="id"
                  :label="product.name || `#${id}`"
                  :value="id"
              />
            </el-select>
          </div>

          <div id="lineChart" style="height:400px;"></div>
        </el-tab-pane>

        <!-- 登录日志标签页 -->
        <el-tab-pane label="Login Logs" name="logs">
          <div class="log-filters">
            <el-form :inline="true">
              <el-form-item label="User ID">
                <el-input-number
                    v-model="logFilters.userId"
                    :min="1"
                    placeholder="Filter by User ID"
                    :controls="false"
                />
              </el-form-item>
              <el-form-item label="Start Date">
                <el-date-picker
                    v-model="logFilters.dateStart"
                    type="datetime"
                    placeholder="Select Start Date"
                    :clearable="true"
                />
              </el-form-item>
              <el-form-item label="End Date">
                <el-date-picker
                    v-model="logFilters.dateEnd"
                    type="datetime"
                    placeholder="Select End Date"
                    :clearable="true"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                    type="primary"
                    @click="fetchLoginLogs"
                    :loading="isLogsLoading"
                >
                  Filter
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table
              :data="loginLogs"
              border
              v-loading="isLogsLoading"
              style="width: 100%"
              height="500"
          >
            <el-table-column prop="userId" label="User ID" width="100" />
            <el-table-column prop="login_time" label="Login Time" width="180">
              <template #default="{row}">
                {{ formatDateTime(row.loginTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="logout_time" label="Logout Time" width="180">
              <template #default="{row}">
                {{ formatDateTime(row.logoutTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="ipAddress" label="IP Address" width="150" />
            <el-table-column label="Session Duration" width="150">
              <template #default="{row}">
                {{ calculateDuration(row.loginTime, row.logoutTime) }}
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref, onMounted, onUnmounted, watch, nextTick, computed, reactive} from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';
import {
  ElMessage,
  ElTable,
  ElTableColumn,
  ElCard,
  ElButton,
  ElStatistic,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption
} from 'element-plus';
import {SalesTrendDTO, AccumulatedSale, LoginLog, LogFilters} from '../../types';

export default defineComponent({
  name: 'Logfile',
  components: { ElTable, ElTableColumn, ElCard, ElButton, ElStatistic, ElDatePicker, ElForm, ElFormItem, ElSelect, ElOption },
  setup() {
    const detailedSale = ref<AccumulatedSale>({
      sale: new Map(),
      totalSales: 0,
      productDetail: new Map()
    });
    const saleTrend = ref<SalesTrendDTO>();
    const startDate = ref<Date>(new Date(new Date().getFullYear() - 1, new Date().getMonth(), new Date().getDate()));
    const endDate = ref<Date>(new Date());
    const selectedProductId = ref<number>(0);
    const isLoading = ref(false);
    const isPredicting = ref(false);
    const predictedData = ref<number[]>([]);
    const showPrediction = ref(false);

    let chartInstance: echarts.ECharts;

    // Computed properties to convert Maps to arrays for template rendering
    const saleEntries = computed(() => {
      return detailedSale.value ? Array.from(detailedSale.value.sale.entries()) : [];
    });

    const productEntries = computed(() => {
      return detailedSale.value ? Array.from(detailedSale.value.productDetail.entries()) : [];
    });

    async function fetchSalesData() {
      isLoading.value = true;
      const sellerId = sessionStorage.getItem('userId')!;
      try {
        const response = await axios.get<AccumulatedSale>(`/api/sales/${sellerId}`);
        detailedSale.value =
            {
              sale: new Map(Object.entries(response.data.sale).map(([k, v]) => [parseInt(k), v])),
              totalSales: response.data.totalSales,
              productDetail: new Map(Object.entries(response.data.productDetail).map(([k, v]) => [parseInt(k), v]))
            };
      } catch (err) {
        console.error(err);
        ElMessage.error('加载销售数据失败');
      } finally {
        isLoading.value = false;
      }
    }

    async function fetchSalesDataWithDateRange() {
      if (!startDate.value || !endDate.value) return ElMessage.error('请选择开始和结束日期');
      if (startDate.value > endDate.value) return ElMessage.error('开始日期不能晚于结束日期');

      isLoading.value = true;
      const sellerId = sessionStorage.getItem('userId')!;
      try {
        const { data } = await axios.get<AccumulatedSale>(`/api/sales/${sellerId}/data-range`, {
          params: { start: startDate.value, end: endDate.value}
        });
        detailedSale.value = {
          sale: new Map(Object.entries(data.sale).map(([k, v]) => [parseInt(k), v])),
          totalSales: data.totalSales,
          productDetail: detailedSale.value?.productDetail || new Map()
        };
      } catch {
        ElMessage.error('加载指定日期销售数据失败');
      } finally {
        isLoading.value = false;
      }
    }

    async function fetchSalesTrend() {
      if (!startDate.value || !endDate.value) {
        return ElMessage.error("请选择开始和结束日期");
      }
      if (startDate.value > endDate.value) {
        return ElMessage.error("开始日期不能晚于结束日期");
      }
      isLoading.value = true;
      try {
        const { data } = await axios.get<SalesTrendDTO>(`/api/sales/${sessionStorage.getItem('userId')}/data-trend`, {
          params: {
            start: startDate.value,
            end: endDate.value,
            timeInterval: 'month',
            productId: selectedProductId.value || undefined
          }
        });
        console.log('Raw API response',data);

        saleTrend.value = {
          saleTrend: new Map(Object.entries(data.saleTrend).map(([k, v]) => [parseInt(k), v])),
          timePoints: data.timePoints
        };
        console.log('Processed saleTrend:', saleTrend.value); // 添加这行
        renderLineChart();
      } catch (e) {
        console.error(e);
        ElMessage.error('获取销售趋势数据失败');
      } finally {
        isLoading.value = false;
      }
    }


// 添加预测方法
    async function predictSales() {
      if (!saleTrend.value) return;

      isPredicting.value = true;
      try {
        // 准备历史销售数据
        let historySales: number[] = [];
        if (selectedProductId.value === 0) {
          // 如果是所有产品，计算总销售额
          const productPrices = detailedSale.value.productDetail;
          historySales = saleTrend.value.timePoints.map((_, timeIndex) => {
            let totalSales = 0;
            saleTrend.value!.saleTrend.forEach((quantities, productId) => {
              const price = productPrices.get(productId)?.price || 0;
              totalSales += (quantities[timeIndex] || 0) * price;
            });
            return totalSales;
          });
        } else {
          // 如果是单个产品，使用销售数量
          historySales = saleTrend.value.saleTrend.get(selectedProductId.value) || [];
        }

        // 获取最后一个时间点作为预测起点
        const lastDate = new Date(saleTrend.value.timePoints[saleTrend.value.timePoints.length - 1]);

        // 修改为GET请求
        const response = await axios.get<number[]>('/api/predict-sales', {
          params: {
            sales: historySales,
            start: lastDate.toISOString()
          },
          paramsSerializer: {
            indexes: null // 保持数组格式
          }
        });

        predictedData.value = response.data;
        showPrediction.value = true;
        renderLineChart();
      } catch (error) {
        console.error('预测失败:', error);
        ElMessage.error('预测销量失败');
      } finally {
        isPredicting.value = false;
      }
    }

    // 修改renderLineChart方法以显示预测数据
    function renderLineChart() {
      if (!saleTrend.value || !detailedSale.value) return;

      const dom = document.getElementById('lineChart')!;
      if (chartInstance) chartInstance.dispose();
      chartInstance = echarts.init(dom);

      // 准备历史数据
      let historyData: number[] = [];
      let chartTitle = '';
      let seriesName = '';
      let yAxisName = '';

      if (selectedProductId.value === 0) {
        // 计算总销售额
        const productPrices = detailedSale.value.productDetail;
        historyData = saleTrend.value.timePoints.map((_, timeIndex) => {
          let totalSales = 0;
          saleTrend.value!.saleTrend.forEach((quantities, productId) => {
            const price = productPrices.get(productId)?.price || 0;
            totalSales += (quantities[timeIndex] || 0) * price;
          });
          return totalSales;
        });
        chartTitle = '总销售额 (所有产品)';
        seriesName = '总销售额';
        yAxisName = '销售额 (元)';
      } else {
        // 单个产品销售数量
        historyData = saleTrend.value.saleTrend.get(selectedProductId.value) || [];
        const productName = detailedSale.value.productDetail.get(selectedProductId.value)?.name || selectedProductId.value.toString();
        chartTitle = `产品 ${productName} 销量`;
        seriesName = `销量`;
        yAxisName = '销量 (件)';
      }

      // 准备x轴数据
      const historyTimePoints = saleTrend.value.timePoints.map(d => {
        const date = new Date(d);
        return `${date.getFullYear()}-${date.getMonth() + 1}`;
      });

      // 修改预测数据部分 - 确保连接点一致
      let predictedTimePoints: string[] = [];
      if (showPrediction.value && predictedData.value.length > 0) {
        const lastDate = new Date(saleTrend.value.timePoints[saleTrend.value.timePoints.length - 1]);
        predictedTimePoints = predictedData.value.map((_, i) => {
          const date = new Date(lastDate);
          date.setMonth(date.getMonth() + i + 1);
          return `${date.getFullYear()}-${date.getMonth() + 1}`;
        });
      }



      // 设置图表选项
      const option = {
        title: {
          text: chartTitle,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params: any) => {
            const data = params[0];
            const isPrediction = data.seriesName.includes('预测');
            const value = data.value;
            const unit = selectedProductId.value === 0 ? '元' : '件';
            return `${data.name}<br/>${data.seriesName}: ${value} ${unit}${isPrediction ? ' (预测)' : ''}`;
          }
        },
        xAxis: {
          type: 'category',
          data: [...historyTimePoints, ...predictedTimePoints]
        },
        yAxis: {
          type: 'value',
          name: yAxisName
        },
        series: [
          {
            name: seriesName,
            type: 'line',
            data: historyData,
            smooth: true,
            itemStyle: {
              color: '#5470C6'
            }
          }
        ],
        grid: { containLabel: true, bottom: '15%' },
        toolbox: { feature: { saveAsImage: {} }, right: 20 },
        dataZoom: [{ type: 'inside' }, { type: 'slider' }]
      };

      // 修改预测系列数据 - 确保连接点一致
      if (showPrediction.value && predictedData.value.length > 0) {
        // 获取历史数据的最后一个值作为连接点
        const lastHistoryValue = historyData[historyData.length - 1];

        option.series.push({
          name: `${seriesName} (预测)`,
          type: 'line',
          // 将历史数据的最后一个值作为预测数据的第一个点
          data: [...Array(historyData.length - 1).fill(null), lastHistoryValue, ...predictedData.value],
          smooth: true,
          itemStyle: {
            color: '#EE6666'
          },
          // 移除虚线样式，或只在预测部分使用虚线
          lineStyle: {
            type: 'dashed',
            // 确保连接点不是虚线
            dashOffset: historyData.length - 1
          },
          // 添加符号标记连接点
          markPoint: {
            data: [
              {
                name: '预测起点',
                value: lastHistoryValue,
                xAxis: historyTimePoints.length - 1,
                yAxis: lastHistoryValue,
                itemStyle: { color: '#EE6666' }
              }
            ]
          }
        });
      }

      chartInstance.setOption(option);
    }

    //LOG逻辑


    const activeTab = ref('sales') // 默认激活销售数据标签页

    // 登录日志相关状态
    const loginLogs = ref<LoginLog[]>([])
    const isLogsLoading = ref(false)

    const logFilters = reactive<LogFilters>({
      userId: null,
      dateStart: new Date(),
      dateEnd: new Date(),
    })


    // 获取登录日志数据
    const fetchLoginLogs = async () => {
      try {
        isLogsLoading.value = true

        // 构造查询参数
        const params = {
          userId: logFilters.userId,
          startDate: logFilters.dateStart?.toISOString(),
          endDate: logFilters.dateEnd?.toISOString()
        }

        // 调用API获取数据
        const response = await axios.get('/api/login-records', { params })
        loginLogs.value = response.data;

      } catch (error) {
        console.error('Failed to fetch login logs:', error)
        // 这里可以添加错误提示
      } finally {
        isLogsLoading.value = false
      }
    }


    const formatDateTime = (date: string | Date): string => {
      if (!date) return 'N/A'
      const d = new Date(date)
      return d.toLocaleString() // 或者使用day.js等库进行更复杂的格式化
    }

    const calculateDuration = (start: string | Date, end: string | Date): string => {
      if (!start || !end) return 'N/A'

      const startTime = new Date(start).getTime()
      const endTime = new Date(end).getTime()
      const diffMs = endTime - startTime

      const hours = Math.floor(diffMs / (1000 * 60 * 60))
      const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))

      return `${hours}h ${minutes}m`
    }
    onMounted(() => {
      fetchSalesData();
      nextTick(() => {
        if (detailedSale.value) {
          fetchSalesTrend();
        }
      });
    });

    onUnmounted(() => {
      if (chartInstance) {
        chartInstance.dispose();
      }
    });

    watch([startDate, endDate], () => {
      if (detailedSale.value) {
        fetchSalesTrend();
      }
    });

    return {
      detailedSale,
      startDate,
      saleTrend,
      endDate,
      isLoading,
      selectedProductId,
      saleEntries,
      productEntries,
      isPredicting,
      showPrediction,
      predictedData,
      fetchSalesDataWithDateRange,
      fetchSalesTrend,
      predictSales,
      // 登录登出信息的返回
      activeTab,
      loginLogs,
      isLogsLoading,
      logFilters,
      fetchLoginLogs,

      formatDateTime,
      calculateDuration

    };
  }
});
</script>

<style scoped>
.sales-container {
  padding: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.date-filter {
  margin-bottom: 20px;
}

.total-sales {
  margin-bottom: 20px;
  text-align: center;
}

.select-product {
  margin-bottom: 20px;
}

#lineChart {
  width: 100%;
  height: 400px;
  margin-top: 20px;
}
.prediction-note {
  margin-top: 10px;
  color: #EE6666;
  font-size: 14px;
  text-align: center;
}
</style>